/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid, column, model } from '../stores/definitions.js';
import ChargeForm from './ChargeForm.jsx';
import TauTable from '@/components/TauTable';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';

const FromItem = Form.Item;

const { relateRoutes } = model;

const ShareShiftSet = ({
  modal,
  onSubmit,
  onCancel,
}) => {
  const { show, record } = modal;
  const { scRelevancyStore: store } = useStore();
  const isViewMode = show === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [relevancy] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [idx, setIdx] = useState(-1);
  const [curCharge, setCurCharge] = useState();
  const [state, setState] = useState([]);

  useEffect(() => { if (modal.toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      await store.getFromCity();
      if (record) {
        const res = await store.get(record.id);
        setState(res.relateRoutes);
        editCtx.origin = _.cloneDeep(res);
        _.assign(relevancy, res);
      } else {
        // 添加操作,设置默认值
        _.set(relevancy, 'enable', true);
      }
    })();
  }, []);

  if (!relevancy) return <></>;

  const handleAddLine = () => {
    setIdx(() => state.length);
    setState((pre) => [...pre]);
    setCurCharge({ schedule: [] });
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(relevancy, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const cloneData = _.cloneDeep(state);
    cloneData[idx] = toJS(values);
    setState(cloneData);
    setCurCharge(false);
  };

  const handleRemoveState = (i) => {
    const cloneState = _.cloneDeep(state);
    cloneState.splice(i, 1);
    setState(cloneState);
  };

  const handleEditState = (r, i) => {
    const cloneState = _.cloneDeep(state);
    setState(cloneState);
    setCurCharge(r);
    setIdx(() => i);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (_value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const cloneState = _.cloneDeep(state);
    _.set(relevancy, 'relateRoutes', cloneState);
    onSubmit?.(relevancy);
  };

  return (
    <>
      <Form
        isPreview={isViewMode}
        {...formProps}
        value={relevancy}
        inline
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <TitleGrid title={t`站点信息`} />
        <FieldsGrid
          formData={relevancy}
          mode={show}
          columns={4}
          fields={['routeName', 'enable']}
        />
        <TitleGrid title={t`关联线路信息`} />
        <FromItem>
          <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddLine()}>{t`添加线路`}</Button>
          <FromItem>
            <TauTable
              primaryKey="id"
              tableLayout="fixed"
              dataSource={state}
              columns={[
                { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
                column('onCityName', { width: 88 }, relateRoutes),
                column('onStationName', { width: 160 }, relateRoutes),
                column('offCityName', { width: 88 }, relateRoutes),
                column('offStationName', { width: 160 }, relateRoutes),
                column('schedule', { width: 150 }, relateRoutes),
                {
                  dataIndex: 'other',
                  width: 100,
                  cell: (v, i, r) => {
                    const menu = [
                      {
                        title: t`编辑`,
                        onClick: () => handleEditState(r, i),
                      },
                      {
                        title: t`删除`,
                        color: 'red',
                        onClick: () => handleRemoveState(i),
                      },
                    ];
                    return <MoreFuncDropDown dropdownItems={menu} />;
                  },
                },
              ]}
              hidePagination
            />
          </FromItem>
        </FromItem>
        <TitleGrid title={t`备注信息`} />
        <FieldsGrid
          formData={relevancy}
          mode={show}
          columns={4}
          fields={['remarks']}
        />
        <DrawerFooter>
          <FromItem>
            {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
      <Dialog
        visible={!!curCharge}
        onCancel={() => setCurCharge(false)}
        onClose={() => setCurCharge(false)}
        title={t`编辑线路`}
        style={{ width: '30%' }}
        footer={null}
      >
        <ChargeForm
          data={curCharge}
          onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
          onCancel={() => setCurCharge(false)}
        />
      </Dialog>
    </>
  );
};

export default observer(ShareShiftSet);
